#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

module Luce
  # Parses atx-style headers: `## Header ##`.
  class HeaderSyntax < BlockSyntax
    def pattern : Regex
      Luce.header_pattern
    end

    def parse(parser : BlockParser) : Node
      # ameba:disable Lint/NotNil
      match = pattern.match(parser.current.content).not_nil!
      matched_text = match[0]
      open_marker = match[1]
      close_marker = match[2]?
      level = open_marker.size
      open_marker_start = matched_text.index(open_marker) || -1
      open_marker_end = open_marker_start + level

      content : String?
      if close_marker.nil?
        content = parser.current.content[open_marker_end..]
      else
        close_marker_start = matched_text.rindex(close_marker) || -1
        content = parser.current.content[open_marker_end...close_marker_start]
      end
      content = content.strip

      # https://spec.commonmark.org/0.30/#example-79
      if close_marker == nil && Regex.new("^#+$").matches?(content)
        content = nil
      end
      parser.advance
      children : Array(Node) = if content.nil?
        [] of Node
      else
        [UnparsedContent.new(content)] of Node
      end
      Element.new("h#{level}", children)
    end
  end
end
